package com.wrial.mall.product.config;
/*
 * @Author  Wrial
 * @Date Created in 10:57 2020/5/26
 * @Description
 */

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@EnableCaching
@Configuration
@EnableConfigurationProperties(CacheProperties.class)//可以获取CacheProperties配置信息，封装为一个Bean
public class MyCacheConfig {

    /**
     * 对于缓存问题的解决
     * 1.读模式
     *      缓存穿透：对null进行缓存
     *      缓存击穿：大并发查同一个请求，加锁
     *      缓存雪崩：大量key同时过期，加随机时间
     *2.写模式
     *      读写加锁
     *      引入Canal，感知DB的更新
     *      读多写多就直接去数据库查
     * 原理：CacheManager（RedisCacheManager）->Cache（RedisCache）->Cache负责读写
     *
     * 总结：常规数据（读多写少，实时性要求不高）完全可以使用SpringCache：写模式有过期时间就足够了
     *      特殊数据需要进行特殊设计
     *
     *
     *
     */




    /**
     * 配置文件的东西没了,需要将配置文件的配置生效
     *
     * @return
     */
    @Bean
    RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();

        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }


        return config;
    }
}
